package com.ruoyi.web.controller.data;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Collections;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.FileZtree;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.FileUtils;
import com.ruoyi.common.utils.LinuxCmdUtil;
import com.ruoyi.common.utils.PrometheusAPIUtils;
import com.ruoyi.common.utils.bean.UsbLog;
import com.ruoyi.system.domain.HdSpaceManage;
import com.ruoyi.system.service.IHdSpaceManageService;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;

/**
 * 页面跳转处理
 * 
 * @author ljw
 */
@Controller
@RequestMapping("/hddata")
public class HDDataController extends BaseController{
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private IHdSpaceManageService hdSpaceManageService;
    /**
     * NAS数据管理-访问流量统计
     */
    @GetMapping("/hdNasSummary")
    public String hdNasSummary()
    {
        return "hddata_service/hd_nas_summary";
    }
    
    /**
     * NAS数据管理-NAS用户登录
     */
    @GetMapping("/hdNasLogin")
    public String hdNasLogin()
    {
        return "hddata_service/hd_nas_login";
    }
    
    /**
     * NAS数据管理-NAS用户管理
     */
    @GetMapping("/hdNasUser")
    public String hdNasUser()
    {
        return "hddata_service/hd_nas_user";
    }
    
    /**
     * 存储管理-逻辑盘符
     */
    @GetMapping("/hdDiskLabel")
    public String hdDiskLabel(ModelMap mmap,HttpServletRequest request)
    {
    	//获取管理分机IP
   	 	//String storageIp = configService.selectConfigByKey("storage_ip");
   	    String manageIp = request.getServerName();
   	 	String diskLabelUrl = "http://"+manageIp+":10011/lvm/index.cgi";
   	 	mmap.put("diskLabelUrl", diskLabelUrl);
        return "hddata_service/hd_disk_label";
    }
    
    /**
     * 存储管理-阵列管理
     */
    @GetMapping("/hdRaidManage")
    public String hdRaidManage(ModelMap mmap,HttpServletRequest request)
    {
    	//获取存储分机IP
   	 	//String storageIp = configService.selectConfigByKey("storage_ip");
   	    String manageIp = request.getServerName();
   	 	String raidUrl = "http://"+manageIp+":10011/raid/";
   	 	mmap.put("raidUrl", raidUrl);
        return "hddata_service/hd_raid_manage";
    }
    
    /**
     * 存储管理-磁盘管理
     */
    @GetMapping("/hdDiskManage")
    public String hdDiskManage(ModelMap mmap,HttpServletRequest request)
    {
    	//获取存储分机IP
   	 	//String storageIp = configService.selectConfigByKey("storage_ip");
   	    String manageIp = request.getServerName();
   	 	String diskManageUrl = "http://"+manageIp+":10011/fdisk/index.cgi";
   	 	mmap.put("diskManageUrl", diskManageUrl);
        return "hddata_service/hd_disk_manage";
    }
    
    /**
     * 存储管理-安全管理
     */
    @GetMapping("/hdSafeManage")
    public String hdSafeManage(ModelMap mmap)
    {	
    	//获取存储分机IP
   	 	String storageIp = configService.selectConfigByKey("storage_ip");
   	 	
   	 	//获取USB日志
    	String cmd = "ssh root@" + storageIp + " cat /home/hdsoft/usb_monitor/usb_log.txt";
		List<UsbLog> usbLogList = LinuxCmdUtil.getUsbLogInfo(cmd);
		String usbLogListStr = null;
		if(usbLogList != null && usbLogList.size() != 0){
			//倒序list
			Collections.reverse(usbLogList);
			
			usbLogListStr = JSONArray.toJSON(usbLogList).toString();
		}
		
		//获取USB状态
		String cmdUsbState = "ssh root@" + storageIp + " cat /home/hdsoft/usb_monitor/usb_now.txt";
		List<UsbLog> usbStateList = LinuxCmdUtil.getUsbStatusInfo(cmdUsbState);
		if(usbStateList == null){
			usbStateList = new ArrayList<UsbLog>();
		}
		
		mmap.addAttribute("usbLogList", usbLogListStr);
		mmap.addAttribute("usbStateList", usbStateList);
    	
        return "hddata_service/hd_safe_manage";
    }
    
    /**
     * 存储管理-安全管理-获取U口状态
     */
    @PostMapping("/changeUsbState")
    @ResponseBody
    public AjaxResult changeUsbState(ModelMap mmap,String usbLocation,String usbPortState,int usbOption)
    {
    	//获取存储分机IP
   	 	String storageIp = configService.selectConfigByKey("storage_ip");
   	 	
    	if(usbLocation == null || "".equals(usbLocation)) {
    		return AjaxResult.error("未传递USB位置，修改失败！");
    	}
    	
    	if(usbPortState == null || "".equals(usbPortState)) {
    		return AjaxResult.error("未传递USB口状态，修改失败！");
    	}
    	
    	String usbOptStr = "";
    	String usbOptStrNew = "";
    	if(usbOption == 2) {//禁用
    		usbOptStr = "true";
    		usbOptStrNew = "false";
    	}else if(usbOption == 1) {//启用
    		usbOptStr = "false";
    		usbOptStrNew = "true";
    	}else {
    		return AjaxResult.error("未传递操作参数，修改失败！");
    	}
    	
    	String oldStr = usbLocation + " " + usbOptStr;
    	String newStr = usbLocation + " " + usbOptStrNew;
    	String cmd = "ssh root@" + storageIp + " " + '"' + "sed -i 's/"+oldStr+"/"+newStr+"/g' /home/hdsoft/usb_monitor/usb_now.txt" + '"';
    	return LinuxCmdUtil.exeLinux(cmd);
    }
    
    /**
     * 存储管理-数据空间管理
     */
    @GetMapping("/hdDataSpace")
    public String hdDataSpace()
    {
        return "hddata_service/hd_data_space";
    }
    
    /**
     * 存储管理-服务管理
     */
    @GetMapping("/hdServerManage")
    public String hdServerManage()
    {
        return "hddata_service/hd_server_manage";
    }
    
    
    /**
     * 存储管理-电源管理
     */
    @GetMapping("/hdPowerManage")
    public String hdPowerManage()
    {
        return "hddata_service/hd_power_manage";
    }
    
    /**
     * 存储管理-电源管理-操作
     */
    @Log(title = "电源操作", businessType = BusinessType.OTHER)
    @PostMapping("/hdPowerOpt")
    @ResponseBody
    public AjaxResult hdPowerOpt(int serverNum,int optNum)
    {
    	String optStr = "";
    	if(optNum == 1) {//关机
    		optStr = "poweroff";
    	}else if(optNum == 2) {//重启
    		optStr = "reboot";
    	}else {
    		return error("操作失败，指令非法！");
    	}
    	
    	String command = null;
    	if(serverNum == 1) {//磁盘阵列
    		//获取存储分机IP
       	 	String storageIp = configService.selectConfigByKey("storage_ip");
    		command = "ssh root@" + storageIp + " " + optStr;
    	}else if(serverNum == 2) {//控制分机
    		command = optStr;
    	}else {
    		return error("操作失败，机器选择非法！");
    	}
    	
        return LinuxCmdUtil.exeLinux(command);
    }
    
    /**
     * 网络管理-磁盘阵列分机
     */
    @GetMapping("/hdSaveNet")
    public String hdSaveNet(ModelMap mmap,HttpServletRequest request)
    {
    	//获取存储分机IP
   	 	//String storageIp = configService.selectConfigByKey("storage_ip");
   	    String manageIp = request.getServerName();
   	 	String saveNetUrl = "http://"+manageIp+":10011/net/list_ifcs.cgi";
   	 	mmap.put("saveNetUrl", saveNetUrl);
   	 	return "hddata_service/hd_save_net";
    }
    
    /**
     * 网络管理-存储控制分机
     */
    @GetMapping("/hdControlNet")
    public String hdControlNet(ModelMap mmap,HttpServletRequest request)
    {
    	//获取管理分机IP
   	 	//String manageIp = configService.selectConfigByKey("manage_ip");
   	    String manageIp = request.getServerName();
   	 	String manageNetUrl = "http://"+manageIp+":10001/net/list_ifcs.cgi";
   	 	mmap.put("manageNetUrl", manageNetUrl);
    	return "hddata_service/hd_control_net";
    }
    
    /**
     * 网络管理-存储控制分机(原始)
     */
    @GetMapping("/hdControlNetBak")
    public String hdControlNetBak(ModelMap mmap)
    {
    	//获取管理分机IP
   	 	String manageIp = configService.selectConfigByKey("manage_ip");
   	 	
   	 	String prometheusPort = configService.selectConfigByKey("prometheus_port");
   	 	
   	 	//查询网卡信息
   	 	JSONObject param = new JSONObject();
   	 	param.put("query", "node_network_info{server_name='存储控制分机'}");
		String result = PrometheusAPIUtils.getHttp("http://" + manageIp + ":" + prometheusPort + "/api/v1/query?query={query}", param);        
	    
//		System.out.println(result);
		JSONObject netJson = JSONObject.parseObject(result);
		//查询Ip信息
		JSONObject paramIp = new JSONObject();
   	 	paramIp.put("query", "node_network_route_info{server_name='存储控制分机'}");
		String resultIp = PrometheusAPIUtils.getHttp("http://" + manageIp + ":" + prometheusPort + "/api/v1/query?query={query}", paramIp);
		JSONObject netJsonIp = JSONObject.parseObject(resultIp);
		
		JSONObject netJson1 = (JSONObject)netJson.get("data");
		List<JSONObject> neJsonList = (List<JSONObject>)netJson1.get("result");
		
		for(JSONObject netJson2 : neJsonList) {
			JSONObject netJson3 = (JSONObject)netJson2.get("metric");
			String deviceName = (String)netJson3.get("device");
			
			//遍历带IP的JSON
			JSONObject netJsonIp1 = (JSONObject)netJsonIp.get("data");
			List<JSONObject> neJsonIpList = (List<JSONObject>)netJsonIp1.get("result");
			for(JSONObject netJsonIp2 : neJsonIpList) {
				JSONObject netJsonIp3 = (JSONObject)netJsonIp2.get("metric");
				String deviceNameIp = (String)netJsonIp3.get("device");
				String deviceIp = (String)netJsonIp3.get("src");
				String deviceIpLabel = (String)netJson3.get("deviceIp");
				
				if(deviceIpLabel == null) {
					netJson3.put("deviceIp", "未知");
				}
				if(deviceName.equals(deviceNameIp) && deviceIp != null) {
					netJson3.put("deviceIp", deviceIp);
				}
			}
		}
		
//		System.out.println("netJsonValue:"+netJson.toJSONString());
		
		mmap.put("netJson", netJson);
       return "hddata_service/hd_control_net";
    }
    
    
    /**
     * 网络管理-磁盘阵列分机(原始)
     */
    @GetMapping("/hdSaveNetBAK")
    public String hdSaveNetBAK(ModelMap mmap)
    {
    	//获取管理分机IP
   	 	String manageIp = configService.selectConfigByKey("manage_ip");
   	 	
   	 	String prometheusPort = configService.selectConfigByKey("prometheus_port");
   	 	
   	 	//查询网卡信息
   	 	JSONObject param = new JSONObject();
   	 	param.put("query", "node_network_info{server_name='磁盘阵列分机'}");
		String result = PrometheusAPIUtils.getHttp("http://" + manageIp + ":" + prometheusPort + "/api/v1/query?query={query}", param);  
		JSONObject netJson = JSONObject.parseObject(result);
		//查询Ip信息
		JSONObject paramIp = new JSONObject();
   	 	paramIp.put("query", "node_network_route_info{server_name='磁盘阵列分机'}");
		String resultIp = PrometheusAPIUtils.getHttp("http://" + manageIp + ":" + prometheusPort + "/api/v1/query?query={query}", paramIp);
		JSONObject netJsonIp = JSONObject.parseObject(resultIp);
		
		JSONObject netJson1 = (JSONObject)netJson.get("data");
		List<JSONObject> neJsonList = (List<JSONObject>)netJson1.get("result");
		
		for(JSONObject netJson2 : neJsonList) {
			JSONObject netJson3 = (JSONObject)netJson2.get("metric");
			String deviceName = (String)netJson3.get("device");
			
			//遍历带IP的JSON
			JSONObject netJsonIp1 = (JSONObject)netJsonIp.get("data");
			List<JSONObject> neJsonIpList = (List<JSONObject>)netJsonIp1.get("result");
			for(JSONObject netJsonIp2 : neJsonIpList) {
				JSONObject netJsonIp3 = (JSONObject)netJsonIp2.get("metric");
				String deviceNameIp = (String)netJsonIp3.get("device");
				String deviceIp = (String)netJsonIp3.get("src");
				String deviceIpLabel = (String)netJson3.get("deviceIp");
				
				if(deviceIpLabel == null) {
					netJson3.put("deviceIp", "未知");
				}
				if(deviceName.equals(deviceNameIp) && deviceIp != null) {
					netJson3.put("deviceIp", deviceIp);
				}
			}
		}
		
//		System.out.println("netJsonValue:"+netJson.toJSONString());
		
		mmap.put("netJson", netJson);
       return "hddata_service/hd_save_net";
    }
    
    /**
     * 获取文件操作页
     */
    @GetMapping("/getFileOperatePage")
    public String getFileOperatePage(ModelMap mmap,HttpServletRequest request)
    {
    	SysUser user = getSysUser();
    	String userName = user.getUserName();
    	String userPass = user.getPassword();
   	    String manageIp = request.getServerName();
   	    String loginName = user.getLoginName();
   	    Long userId = user.getUserId();
   	    String filePath = "";
    	//获取管理分机真实IP
   	 	String manageIpReal = configService.selectConfigByKey("manage_ip");
   	    
   	    HdSpaceManage hsmQuery = new HdSpaceManage();
   	    hsmQuery.setBelongUserId(userId);
   	    List<HdSpaceManage> hsmQueryResult = hdSpaceManageService.selectHdSpaceManageListForFileOperate(hsmQuery);
   	    String errorMsg = "";
   	    if(hsmQueryResult == null || hsmQueryResult.size() == 0) {
   	    	errorMsg = userName + "，您当前无可用空间，请联系管理员为您创建个人空间！";
   	    	mmap.put("errorMsg", errorMsg);
   	    	return "hddata_service/file_operate_error";
   	    }
    	if(hsmQueryResult != null && hsmQueryResult.size() > 1) {
    		errorMsg = userName + "，您当前激活多个空间，请联系管理员为您停用多余空间！";
    		mmap.put("errorMsg", errorMsg);
   	    	return "hddata_service/file_operate_error";
    	}
    	if(manageIpReal == null || "".equals(manageIpReal)) {
    		errorMsg = userName + "，请联系管理员配置好存储阵列IP以及管理分机IP！";
    		mmap.put("errorMsg", errorMsg);
   	    	return "hddata_service/file_operate_error";
    	}
    	
    	filePath = hsmQueryResult.get(0).getSpacePath();
   	    
   	 	String fileOperateUrl = "http://"+manageIp+":8098/getFileManagePage?userName="+userName+"&userPass="+userPass+"&filePath="+filePath+"&manageIpReal="+manageIpReal+"&loginName="+loginName;
   	 	mmap.put("fileOperateUrl", fileOperateUrl);
        return "hddata_service/file_operate";
    }
    
    /**
     * 创建阵列
     */
    @GetMapping("/createRaidPage")
    public String createRaidPage()
    {
        return "hddata_service/create_raid_page";
    }
    
    /**
     * 创建数据空间
     */
    @GetMapping("/createDataSpace")
    public String createDataSpace(ModelMap mmap)
    {
    	
    	List<HdSpaceManage> spaceManageList = new ArrayList<>();
    	
    	try {
    		//获取管理分机IP
       	 	String manageIp = configService.selectConfigByKey("manage_ip");
       	 	
       	 	String prometheusPort = configService.selectConfigByKey("prometheus_port");
       	 	
       	 	//查询挂载设备总空间
       	 	JSONObject paramSpaceTotal = new JSONObject();
       	 	paramSpaceTotal.put("query", "node_filesystem_size_bytes{server_name='磁盘阵列分机'}");
    		String resultSpaceTotal = PrometheusAPIUtils.getHttp("http://" + manageIp + ":" + prometheusPort + "/api/v1/query?query={query}", paramSpaceTotal);  
    		JSONObject spaceTotalJson = JSONObject.parseObject(resultSpaceTotal);
    		
    		//查询挂载设备剩余空间
    		JSONObject paramSpaceFree = new JSONObject();
    		paramSpaceFree.put("query", "node_filesystem_avail_bytes{server_name='磁盘阵列分机'}");
    		String resultSpaceFree = PrometheusAPIUtils.getHttp("http://" + manageIp + ":" + prometheusPort + "/api/v1/query?query={query}", paramSpaceFree);  
    		JSONObject spaceFreeJson = JSONObject.parseObject(resultSpaceFree);
    		
    		//解析JSON
    		JSONObject spaceTotalJson1 = (JSONObject)spaceTotalJson.get("data");
    		List<JSONObject> spaceTotalJsonList = (List<JSONObject>)spaceTotalJson1.get("result");
    		
    		JSONObject spaceFreeJson1 = (JSONObject)spaceFreeJson.get("data");
    		List<JSONObject> spaceFreeJsonList = (List<JSONObject>)spaceFreeJson1.get("result");
    		
    		for(JSONObject spaceTotalJson2 : spaceTotalJsonList) {
    			JSONObject spaceTotalJson3 = (JSONObject)spaceTotalJson2.get("metric");
    			
    			List<String> spaceTotalJsonValue = (List<String>)spaceTotalJson2.get("value");
    			
    			String deviceName = (String)spaceTotalJson3.get("device");//挂载设备
    			String fstype = (String)spaceTotalJson3.get("fstype");//文件系统格式
    			String mountpoint = (String)spaceTotalJson3.get("mountpoint");//挂载路径
    			String spaceTotalValue = spaceTotalJsonValue.get(1);
    			String spaceFreeValue = "0";
//    			System.out.println("value:"+spaceTotalJsonValue.toString());
//    			System.out.println("deviceName:"+deviceName);
//    			System.out.println("fstype:"+fstype);
//    			System.out.println("mountpoint:"+mountpoint);
    			
    			for(JSONObject spaceFreeJson2 : spaceFreeJsonList) {
    				JSONObject spaceFreeJson3 = (JSONObject)spaceFreeJson2.get("metric");
    				
    				String deviceNameFree = (String)spaceFreeJson3.get("device");//挂载设备
    				String mountpointFree = (String)spaceFreeJson3.get("mountpoint");//挂载路径
    				if(mountpointFree.equals(mountpoint) && deviceNameFree.equals(deviceName)) {//如果挂载路径和挂载设备相同
    					List<String> spaceFreeJsonValue = (List<String>)spaceFreeJson2.get("value");
    					spaceFreeValue = spaceTotalJsonValue.get(1);//剩余容量
    				}
    				
    				
    			}
    			
    			Long spaceTotalLong = Long.parseLong(spaceTotalValue)/1024/1024/1024;//bytes转GiB
    			Long spaceFreeLong = Long.parseLong(spaceFreeValue)/1024/1024/1024;//bytes转GiB
    			
    			HdSpaceManage hsm = new HdSpaceManage();
    			hsm.setSpaceDeviceName(deviceName);
    			hsm.setSpacePath(mountpoint);
    			hsm.setSpaceTotalVolume(spaceTotalLong);
    			hsm.setSpaceFreeVolume(spaceFreeLong);
    			if(spaceFreeLong != 0) {
    				spaceManageList.add(hsm);
    			}    			
    		}
		} catch (Exception e) {
			// TODO: handle exception
			HdSpaceManage hsm = new HdSpaceManage();
			hsm.setSpaceDeviceName("无可用设备");
			hsm.setSpacePath("");
			hsm.setSpaceTotalVolume(0L);
			hsm.setSpaceFreeVolume(0L);
			spaceManageList.add(hsm);
		}
    	
		//获取用户列表
		List<SysUser> userList = userService.selectAllUserList();
		
		mmap.put("userList", userList);
    	mmap.put("spaceManageList", spaceManageList);
        return "hddata_service/create_space_page";
    }
    
    /**
     * 新增数据空间
     */
    @Log(title = "新增数据空间", businessType = BusinessType.INSERT)
    @PostMapping("/addDataSpace")
    @ResponseBody
    public AjaxResult addDataSpace(HdSpaceManage hdSpaceManage)
    {
    	if(hdSpaceManage == null) {
    		return AjaxResult.error("未传递参数，新增失败！");
    	}
    	
    	if(hdSpaceManage.getSpacePath() == null || "".equals(hdSpaceManage.getSpacePath())) {
    		return AjaxResult.error("新增失败，请选择有效存储空间！");
    	}
    	
    	hdSpaceManage.setSpaceDeleteFlag("0");
    	
    	//设置空间所属用户名称
    	Long belongUserId = hdSpaceManage.getBelongUserId();
    	if(belongUserId != null && belongUserId != 0) {
    		SysUser sysUser = userService.selectUserById(belongUserId);
    		hdSpaceManage.setBelongUserName(sysUser.getUserName());
    	}
    	
    	
        return toAjax(hdSpaceManageService.insertHdSpaceManage(hdSpaceManage));
    }
    
    /**
     * 修改数据空间管理
     */
    @GetMapping("/editSpace/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        HdSpaceManage hdSpaceManage = hdSpaceManageService.selectHdSpaceManageById(id);
        mmap.put("hdSpaceManage", hdSpaceManage);
        return "hddata_service/edit_space_page";
    }
    
    /**
     * 修改保存数据空间管理
     */
    @Log(title = "数据空间管理", businessType = BusinessType.UPDATE)
    @PostMapping("/editSpaceSave")
    @ResponseBody
    public AjaxResult editSave(HdSpaceManage hdSpaceManage)
    {
        return toAjax(hdSpaceManageService.updateHdSpaceManage(hdSpaceManage));
    }
    
    /**
     * 删除数据空间管理
     */
    @Log(title = "数据空间管理", businessType = BusinessType.DELETE)
    @PostMapping( "/removeSpace")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(hdSpaceManageService.deleteHdSpaceManageByIds(ids));
    }
    
    /**
     * 数据空间启用状态修改
     */
    @Log(title = "数据空间管理", businessType = BusinessType.UPDATE)
    @PostMapping("/changeDataSpaceStatus")
    @ResponseBody
    public AjaxResult changeDataSpaceStatus(String spaceId,String stopFlag)
    {
    	HdSpaceManage hdSpaceManage = new HdSpaceManage();
    	
    	if(spaceId == null || "".equals(spaceId) || stopFlag == null || "".equals(stopFlag)) {
    		return error("操作失败，参数非法！");
    	}
    	try {
    		hdSpaceManage.setId(Long.parseLong(spaceId));
        	hdSpaceManage.setSpaceStopFlag(stopFlag);
		} catch (Exception e) {
			// TODO: handle exception
			return error("操作失败，空间ID非法！");
		}
    	
        return toAjax(hdSpaceManageService.updateHdSpaceManage(hdSpaceManage));
    }
    
    /**
     * 查询数据空间列表
     */
    @PostMapping("/dataSpaceList")
    @ResponseBody
    public TableDataInfo dataSpaceList(HdSpaceManage hdSpaceManage)
    {
        startPage();
        List<HdSpaceManage> list = hdSpaceManageService.selectHdSpaceManageList(hdSpaceManage);
        return getDataTable(list);
    }
    
    /**
     * 设备接入申请界面
     */
    @GetMapping("/applyDevice")
    public String applyDevice()
    {
        return "hddata_service/creat_device_apply_page";
    }
    
    /**
     * 管理工具-proFTPD服务器
     */
    @GetMapping("/proFTPDServer")
    public String proFTPDServer(ModelMap mmap,HttpServletRequest request)
    {
    	//获取存储分机IP
   	 	//String storageIp = configService.selectConfigByKey("storage_ip");
    	//String manageIp = "192.168.43.11";
   	    String manageIp = request.getServerName();
   	 	String frameUrl = "http://"+manageIp+":10011/proftpd";
   	 	mmap.put("frameUrl", frameUrl);
   	 	return "hddata_frame/proftpd_server";
    }
    
    /**
     * 管理工具-iscsiTgtd
     */
    @GetMapping("/iscsiTgtd")
    public String iscsiTgtd(ModelMap mmap,HttpServletRequest request)
    {
    	//获取存储分机IP
   	 	//String storageIp = configService.selectConfigByKey("storage_ip");
    	//String manageIp = "192.168.43.11";
   	    String manageIp = request.getServerName();
   	 	String frameUrl = "http://"+manageIp+":10011/iscsi-tgtd";
   	 	mmap.put("frameUrl", frameUrl);
   	 	return "hddata_frame/iscsi_tgtd";
    }
    
    /**
     * 管理工具-samba共享管理器
     */
    @GetMapping("/sambaShare")
    public String sambaShare(ModelMap mmap,HttpServletRequest request)
    {
    	//获取存储分机IP
   	 	//String storageIp = configService.selectConfigByKey("storage_ip");
    	//String manageIp = "192.168.43.11";
   	    String manageIp = request.getServerName();
   	 	String frameUrl = "http://"+manageIp+":10011/samba";
   	 	mmap.put("frameUrl", frameUrl);
   	 	return "hddata_frame/samba_share";
    }
    
    /**
     * 管理工具-磁盘和网络文件系统
     */
    @GetMapping("/diskNetFilesystem")
    public String diskNetFilesystem(ModelMap mmap,HttpServletRequest request)
    {
    	//获取存储分机IP
   	 	//String storageIp = configService.selectConfigByKey("storage_ip");
    	//String manageIp = "192.168.43.11";
   	    String manageIp = request.getServerName();
   	 	String frameUrl = "http://"+manageIp+":10011/mount";
   	 	mmap.put("frameUrl", frameUrl);
   	 	return "hddata_frame/disk_net_filesystem";
    }
    
    /**
     * 管理工具-NFS输出
     */
    @GetMapping("/nfsOutput")
    public String nfsOutput(ModelMap mmap,HttpServletRequest request)
    {
    	//获取存储分机IP
   	 	//String storageIp = configService.selectConfigByKey("storage_ip");
    	//String manageIp = "192.168.43.11";
   	    String manageIp = request.getServerName();
   	 	String frameUrl = "http://"+manageIp+":10011/exports";
   	 	mmap.put("frameUrl", frameUrl);
   	 	return "hddata_frame/nfs_output";
    }
    
    /**
     * 管理工具-用户与群组
     */
    @GetMapping("/userAdmin")
    public String userAdmin(ModelMap mmap,HttpServletRequest request)
    {
    	//获取存储分机IP
   	 	//String storageIp = configService.selectConfigByKey("storage_ip");
    	//String manageIp = "192.168.43.11";
   	    String manageIp = request.getServerName();
   	 	String frameUrl = "http://"+manageIp+":10011/useradmin";
   	 	mmap.put("frameUrl", frameUrl);
   	 	return "hddata_frame/system_user";
    }
    
    /**
     * 存储管理-OMV页面嵌入
     */
    @GetMapping("/omvManage")
    public String omvManage(ModelMap mmap,HttpServletRequest request)
    {
    	//获取存储分机IP
   	 	//String storageIp = configService.selectConfigByKey("storage_ip");
    	//String manageIp = "192.168.43.11";
   	    String manageIp = request.getServerName();
   	 	String frameUrl = "https://"+manageIp+":10012/arrowpoint.html";//
   	 	mmap.put("frameUrl", frameUrl);
   	 	return "hddata_frame/omv_page";
    }
    
    /**
     * 管理工具-远程复制
     */
    @GetMapping("/remoteCopy")
    public String remoteCopy(ModelMap mmap,HttpServletRequest request)
    {
    	//获取存储分机IP
   	 	//String storageIp = configService.selectConfigByKey("storage_ip");
    	//String manageIp = "192.168.43.11";
   	    String manageIp = request.getServerName();
   	 	return "hddata_service/hd_copy_file";
    }
    
    /**
     * 管理工具-风扇控制
     */
    @GetMapping("/fanControl")
    public String fanControl(ModelMap mmap,HttpServletRequest request)
    {
    	//获取存储分机IP
   	 	String storageIp = configService.selectConfigByKey("storage_ip");
    	//String manageIp = "192.168.43.11";
    	String command = "ssh root@"+storageIp+" sysmonitoragent -f get";
    	String fanM = LinuxCmdUtil.getFanM(command);
   	    //String manageIp = request.getServerName();
    	mmap.put("fanM", fanM);
   	 	return "hddata_service/hd_fan_control";
    }
    
    /**
     * 管理工具-风扇控制-获取转速
     */
    @PostMapping("/getFanState")
    @ResponseBody
    public int[] getFanState(ModelMap mmap,HttpServletRequest request)
    {
    	//获取存储分机IP
   	 	String storageIp = configService.selectConfigByKey("storage_ip");
    	//String manageIp = "192.168.43.11";
    	
    	//String command = "ssh root@"+storageIp+" sysmonitoragent -n 1";
   	 	String command = "ssh root@"+storageIp+" sysmonitoragent -f get";
    	int[] result = LinuxCmdUtil.getFanV(command);
   	    //String manageIp = request.getServerName();
   	    //int[] result = {11,11,11,11,11,11,11,11};
//   	    for(int i=0 ; i < 8; i++) {
//   	    	Random rand = new Random();
//   	    	result[i] = rand.nextInt(100) + 1;
//   	    }
   	    
   	 	return result;
    }
    
    /**
     * 管理工具-风扇控制-设置风扇转速
     */
    @Log(title = "设置风扇转速", businessType = BusinessType.UPDATE)
    @PostMapping("/setFanV")
    @ResponseBody
    public AjaxResult setFanV(String fanV,String fanM)
    {
    	//获取存储分机IP
   	 	String storageIp = configService.selectConfigByKey("storage_ip");
    	String command = "";
    	
    	if(fanM == null) {
    		return error("未指定模式，设置失败！");
    	}
    	if("0".equals(fanM)) {//自动
    		command = "ssh root@"+storageIp+" sysmonitoragent -f set 0";
    	}else if("1".equals(fanM)) {//手动
    		try {
				int fanVInt = Integer.parseInt(fanV);
				if(fanVInt > 0 && fanVInt < 101) {//合法
					command = "ssh root@"+storageIp+" sysmonitoragent -f set 1 " + fanVInt + " " +fanVInt + " " +fanVInt + " " +fanVInt;
				}else {
					return error("指定手动模式，必须设置风扇转速，风扇转速设置非法！");
				}
			} catch (Exception e) {
				// TODO: handle exception
				return error("指定手动模式，必须设置风扇转速！");
			}
    	}else {
    		return error("指定模式非法，设置失败！");
    	}
    	
        return LinuxCmdUtil.fanControl(command);
    }
    
    /**
     * 管理工具-风扇控制
     */
    @GetMapping("/fanControlLocal")
    public String fanControlLocal(ModelMap mmap,HttpServletRequest request)
    {
    	//获取存储分机IP
   	 	String storageIp = configService.selectConfigByKey("storage_ip");
    	//String manageIp = "192.168.43.11";
    	String command = "sysmonitoragent -f get";
    	String fanM = LinuxCmdUtil.getFanM(command);
   	    //String manageIp = request.getServerName();
    	mmap.put("fanM", fanM);
   	 	return "hddata_service/hd_fan_control_local";
    }
    
    /**
     * 管理工具-风扇控制-获取转速
     */
    @PostMapping("/getFanStateLocal")
    @ResponseBody
    public int[] getFanStateLocal(ModelMap mmap,HttpServletRequest request)
    {
    	//获取存储分机IP
   	 	String storageIp = configService.selectConfigByKey("storage_ip");
    	//String manageIp = "192.168.43.11";
    	
    	//String command = "ssh root@"+storageIp+" sysmonitoragent -n 1";
   	 	String command = "sysmonitoragent -f get";
    	int[] result = LinuxCmdUtil.getFanV(command);
   	    //String manageIp = request.getServerName();
   	    //int[] result = {11,11,11,11,11,11,11,11};
//   	    for(int i=0 ; i < 8; i++) {
//   	    	Random rand = new Random();
//   	    	result[i] = rand.nextInt(100) + 1;
//   	    }
   	    
    	//临时管控
    	result[1] = result[2];
    	result[2] = 0;
    	result[3] = 0;
    	
   	 	return result;
    }
    
    /**
     * 管理工具-风扇控制-设置风扇转速
     */
    @Log(title = "设置风扇转速", businessType = BusinessType.UPDATE)
    @PostMapping("/setFanVLocal")
    @ResponseBody
    public AjaxResult setFanVLocal(String fanV,String fanM)
    {
    	//获取存储分机IP
   	 	String storageIp = configService.selectConfigByKey("storage_ip");
    	String command = "";
    	
    	if(fanM == null) {
    		return error("未指定模式，设置失败！");
    	}
    	if("0".equals(fanM)) {//自动
    		command = "sysmonitoragent -f set 0";
    	}else if("1".equals(fanM)) {//手动
    		try {
				int fanVInt = Integer.parseInt(fanV);
				if(fanVInt > 0 && fanVInt < 101) {//合法
					command = "sysmonitoragent -f set 1 " + fanVInt + " " +fanVInt + " " +fanVInt + " " +fanVInt;
				}else {
					return error("指定手动模式，必须设置风扇转速，风扇转速设置非法！");
				}
			} catch (Exception e) {
				// TODO: handle exception
				return error("指定手动模式，必须设置风扇转速！");
			}
    	}else {
    		return error("指定模式非法，设置失败！");
    	}
    	
        return LinuxCmdUtil.fanControl(command);
    }
    
    /**
     * 管理工具-远程复制 获取文件列表
     */
    @GetMapping("/getRemoteFile")
    @ResponseBody
    public List<FileZtree> getRemoteFile(ModelMap mmap,HttpServletRequest request,String srcPath)
    {
    	//获取存储分机IP
   	 	String storageIp = configService.selectConfigByKey("storage_ip");
    	//String manageIp = "192.168.43.11";
   	    //String manageIp = request.getServerName();
   	    
   	    //List<FileZtree> fileZtree = new ArrayList<FileZtree>();
   	    
   	    if(srcPath == null || "".equals(srcPath)) {
   	    	srcPath = "/";
   	    }
   	    
   	    //获取远程服务器文件列表
   	 	JSONObject paramSpaceTotal = new JSONObject();
   	 	paramSpaceTotal.put("srcPath", srcPath);
		String resultSpaceTotal = PrometheusAPIUtils.getHttp("http://" + storageIp + ":8098/getRemoteFile?srcPath={srcPath}", paramSpaceTotal);
   	    
		List<FileZtree> fileZtree = JSONObject.parseArray(resultSpaceTotal, FileZtree.class);		
//   	    List<File> results = FileUtils.getFileList(srcPath);
//		for(File file : results) {
//			FileZtree fz = new FileZtree();
//			boolean isParent = false;
//			if(file.isDirectory()) {
//				isParent = true;
//			}
//			fz.setId(file.getPath());
//			fz.setpId(srcPath);
//			fz.setIsParent(isParent);
//			fz.setName(file.getName());
//			fz.setTitle(file.getName());
//			fileZtree.add(fz);
//		}
   	    
   	 	return fileZtree;
    }
    
    /**
     * 管理工具-远程复制  执行复制命令
     */
    @PostMapping("/excuteCopy")
    @ResponseBody
    public AjaxResult excuteCopy(ModelMap mmap,HttpServletRequest request,String remoteIp,String userName,String userPassWord,String remotePath,String ztreeList)
    {
    	//获取存储分机IP
   	 	String storageIp = configService.selectConfigByKey("storage_ip");
    	//String manageIp = "192.168.43.11";
   	    //String manageIp = request.getServerName();
   	    
   	    if(remoteIp == null || "".equals(remoteIp)) {
   	    	return AjaxResult.error("远程IP地址输入非法！");
   	    }
   	    if(userName == null || "".equals(userName)) {
   	    	return AjaxResult.error("远程系统用户名输入非法！");
	    }
   	    if(userPassWord == null || "".equals(userPassWord)) {
   	    	return AjaxResult.error("远程系统用户密码输入非法！");
	    }
   	    if(remotePath == null || "".equals(remotePath)) {
   	    	return AjaxResult.error("远程系统存储路径输入非法！");
	    }
   	    
   	    //执行远程复制命令
   	 	JSONObject paramSpaceTotal = new JSONObject();
   	 	paramSpaceTotal.put("remoteIp", remoteIp);
   	 	paramSpaceTotal.put("userName", userName);
   	 	paramSpaceTotal.put("userPassWord", userPassWord);
   	 	paramSpaceTotal.put("remotePath", remotePath);
   	 	paramSpaceTotal.put("ztreeList", ztreeList);
		String excutResult = PrometheusAPIUtils.getHttp("http://" + storageIp + ":8098/excuteCopy?remoteIp={remoteIp}&userName={userName}&userPassWord={userPassWord}&remotePath={remotePath}&ztreeList={ztreeList}&", paramSpaceTotal);
		if(excutResult.contains("复制失败")) {
			return AjaxResult.error(excutResult);
		}
//   	    try {
//   	    	List<FileZtree> filsZtreeList = JSONObject.parseArray(ztreeList, FileZtree.class);
//   	    	if(filsZtreeList == null || filsZtreeList.isEmpty()) {
//      	    	 return AjaxResult.error("请在左侧文件树选择要复制的文件！");
//      	    }
//   	    	for(FileZtree fileZtree : filsZtreeList) {
//   	    		String command = "sshpass -p "+userPassWord+" scp -o StrictHostKeychecking=no " + fileZtree.getId() + " "+userName+"@"+remoteIp+":"+remotePath;
//   	    		System.out.println("执行命令：【" + command + "】");
//   	        	AjaxResult excuteRsult = LinuxCmdUtil.exeLinux(command);
//   	        	if(excuteRsult.isError()) {
//   	        		//return error("修改参数'" + config.getConfigName() + "'失败，原因："+excuteRsult.toString());
//   	        		System.out.println("复制文件【"+fileZtree.getId() + "】失败，原因【" + excuteRsult.toString() +"】");
//   				}
//   	    	}
//		} catch (Exception e) {
//			// TODO: handle exception
//			return AjaxResult.error("文件解析错误！");
//		}
   	    
//   	 	return AjaxResult.success("远程复制命令执行成功！");
		return AjaxResult.success(excutResult);
    }
    
}
